package com.gong.gongcloudpicture1.controller;


import com.gong.gongcloudpicture1.annotation.AuthCheck;
import com.gong.gongcloudpicture1.common.BaseResponse;
import com.gong.gongcloudpicture1.constant.UserConstant;
import com.gong.gongcloudpicture1.exception.BusinessException;
import com.gong.gongcloudpicture1.exception.ErrorCode;
import com.gong.gongcloudpicture1.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;


/**
 * 文件上传
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {


    @Resource
    private CosManager cosManager;


    /**
     * 测试上传
     *
     * @param multipartFile
     * @return
     */
    @AuthCheck(mastRole = UserConstant.ADMIN)
    @PostMapping("/test/upload")
    //@RequestPart("file") 当前属性注解是接收表单传输过来的文件
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        //文件名称
        String filename = multipartFile.getOriginalFilename();
        //文件路径
        String filepath = String.format("/test/%s", filename);
        File file = null;
        try {
            //将multipartFile转换成一个临时文件
            file = File.createTempFile(filepath, null);
            //将multipartFile的内容传输到file中
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            return BaseResponse.success(filepath);
        } catch (Exception e) {
            log.error("file upload error" + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error" + filepath);
                }
            }
        }
    }


    /**
     * 测试下载
     *
     * @param filepath 文件路径
     * @param response 响应对象
     */
    @AuthCheck(mastRole = UserConstant.ADMIN)
    @PostMapping("/test/download")
    public void testDownloadFile(String filepath, HttpServletResponse response) throws Exception {
        COSObjectInputStream cosObjectInputStream = null;
        try {
            COSObject object = cosManager.getObject(filepath);
            //得到图片的输入流
            cosObjectInputStream = object.getObjectContent();
            //设置响应头, 让浏览器直到要下载图片
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filepath);
            //将图片输入流写入相应流中
            response.getOutputStream().write(cosObjectInputStream.readAllBytes());
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("download file error" + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载失败");
        } finally {
            if (cosObjectInputStream != null) {
                cosObjectInputStream.close();
            }
        }
    }


}
